{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.09ce1984eb0ed6d6df4f811ff8ef3ade.315360000.1910355625.282335-21426841', 'expires_in': 2592000, 'session_key': '9mzdDAJ072ql/4CjoHJponBxs5NphE8DC6RSaopDKl53i/rGLyXQKWF2t1cWvagj/DZHXj3+GlRxojF3waZ1vqhCrWOB6w==', 'access_token': '24.772020a7619eb75deadc0937074cc191.2592000.1597587625.282335-21426841', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope picchain_test_picchain_api_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理', 'session_secret': '06b3a400e1c798dba3d4451a4fdb2807'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=aKmrtTm5x34UlWqhNOpGf64L&client_secret=YHBaTb4PyX3WxxOVxPToMNXWAfYI9EPl'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "import requests\n",
    "import time\n",
    "\n",
    "APP_ID = '21426841' # 你申请的APP_ID\n",
    "API_KEY = 'aKmrtTm5x34UlWqhNOpGf64L' # 你申请的API_KEY\n",
    "SECRET_KEY = 'YHBaTb4PyX3WxxOVxPToMNXWAfYI9EPl' # # 你申请的SECRET_KEY\n",
    "\n",
    "def get_access_token(cltid, srt_key): # 获取访问令牌\n",
    "    # oauth_url = 'https://openapi.baidu.com/oauth/2.0/token'\n",
    "    oauth_url = 'https://aip.baidubce.com/oauth/2.0/token'\n",
    "    args_data = {'grant_type': 'client_credentials',\n",
    "                 'client_id': cltid,\n",
    "                 'client_secret': srt_key,\n",
    "                 }\n",
    "    cnt_type = {'Content-Type': 'application/json; charset=UTF-8'}\n",
    "    resp = requests.post(oauth_url, data=args_data, headers=cnt_type)\n",
    "    print(\"get baidu center info...\")\n",
    "    if resp.status_code != 200:\n",
    "        print(\"have http error\", resp.status_code)\n",
    "        return None\n",
    "    cnt = resp.json()  # 获取的内容变为字典\n",
    "    cnt['expires_in'] += int(time.time())  # 将有效期时间记录\n",
    "    with open('baidu.ck', 'w', encoding='utf-8') as fp:\n",
    "        res = {'access_token': cnt['access_token'], 'expires_in': cnt['expires_in']}\n",
    "        json.dump(res, fp)\n",
    "    return cnt['access_token']\n",
    "\n",
    "def upload_audio_file(access_token): # 上传你要识别的音频文件，得按照人家规定的参数和格式\n",
    "    # speed_url = 'http://vop.baidu.com/server_api'\n",
    "    speed_url = 'https://aip.baidubce.com/rpc/2.0/session/offline/upload/asr?access_token={%s}' % access_token\n",
    "    # args_data = {'format': 'pcm',\n",
    "    #              'rate': 8000,\n",
    "    #              'channel': 1,\n",
    "    #              'cuid': 'rocky_shop',  # 应用名称，可随意取名\n",
    "    #              'token': atoken,\n",
    "    #              }\n",
    "    args_data = {\n",
    "        \"appId\": APP_ID,\n",
    "        \"companyName\": \"百度\", # 这个可以修改\n",
    "        \"callId\": \"20e59200-57da-423e-b613-6a8ce126d0a7\", # 这个也可以改\n",
    "        \"agentFileUrl\": \"https://gitee.com/attempt/API/raw/master/%E4%BB%A3%E7%A0%81/%E6%B5%8B%E8%AF%95.mp3\", # 你语音文件的url，要公网可访问的地址，你写上之后可以自己先下载试一下\n",
    "        \"suffix\": \"wav\",\n",
    "    }\n",
    "    header = {'Content-Type': 'application/json'}\n",
    "    resp = requests.post(speed_url, data=json.dumps(args_data), headers=header)\n",
    "    info = resp.json()\n",
    "    return info\n",
    "\n",
    "def get_text_from_url(access_token): # 获取识别结果。免费用户是整点识别，上传之后得等待...\n",
    "    datas = {\n",
    "        \"category\": \"OFFLINE_ASR_RESULT\",\n",
    "        \"paras\": {\n",
    "            \"appId\": APP_ID,  # 百度云appId,必选\n",
    "            \"callId\": \"20e59200-57da-423e-b613-6a8ce126d0a7\"  # 用户上传某一通的callId,必选\n",
    "        }\n",
    "    }\n",
    "    data_url = 'https://aip.baidubce.com/rpc/2.0/search/info?access_token={%s}' % access_token\n",
    "    header = {'Content-Type': 'application/json'}\n",
    "    response = requests.post(data_url, data=json.dumps(datas), headers=header)\n",
    "    information = response.json()\n",
    "    return information\n",
    "\n",
    "\n",
    "access_token = get_access_token(API_KEY, SECRET_KEY)\n",
    "print(access_token)\n",
    "info = upload_audio_file(access_token)\n",
    "print(info)\n",
    "result = get_text_from_url(access_token)\n",
    "print(result)\n",
    "# tmp = result['data']['content']\n",
    "# print(tmp)\n",
    "# tmp_list = eval(tmp)\n",
    "# for x in tmp_list:\n",
    "#     print(x['sentence'])\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
